package net.lab1024.sa.admin.module.system.user.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.amount.dao.AmountDao;
import net.lab1024.sa.admin.module.business.amount.domain.entity.AmountEntity;
import net.lab1024.sa.admin.module.business.order.dao.OrderDao;
import net.lab1024.sa.admin.module.business.order.domain.vo.OrderVO;
import net.lab1024.sa.admin.module.system.employee.domain.entity.EmployeeEntity;
import net.lab1024.sa.admin.module.system.role.service.RoleService;
import net.lab1024.sa.admin.module.system.type.Dao.TypeDao;
import net.lab1024.sa.admin.module.system.type.domain.TypeEntity;
import net.lab1024.sa.admin.module.system.user.dao.UserDao;
import net.lab1024.sa.admin.module.system.user.domain.Enity.UserEntity;
import net.lab1024.sa.admin.module.system.user.domain.JdyVO;
import net.lab1024.sa.admin.module.system.user.domain.RequestUser;
import net.lab1024.sa.admin.module.system.user.domain.UserVO;
import net.lab1024.sa.admin.module.system.user.domain.form.UserAddForm;
import net.lab1024.sa.admin.module.system.user.domain.form.UserQueryForm;
import net.lab1024.sa.admin.module.system.user.domain.form.UserUpdateForm;
import net.lab1024.sa.admin.util.IdGenerator;
import net.lab1024.sa.admin.util.MobileRequestUtil;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private TypeDao typeDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private AmountDao amountDao;
    public static Boolean UPDATE = false;
//    @Resource
//    private ShopRangeDao shopRangeDao;
    public ResponseDTO<PageResult<UserVO>> queryUserPage(UserQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<UserVO> entityList = userDao.queryByPage(page, queryForm);
        PageResult<UserVO> pageResult = SmartPageUtil.convert2PageResult(page, entityList, UserVO.class);
        return ResponseDTO.ok(pageResult);
    }
    public ResponseDTO<PageResult<JdyVO>> queryjdy(UserQueryForm QueryForm) {
//        employeeQueryForm.setDeletedFlag(false);
        Page pageParam = SmartPageUtil.convert2PageQuery(QueryForm);
        List<UserVO> userList = userDao.queryByPage(pageParam, QueryForm);
        List<JdyVO> jdyList = SmartBeanUtil.copyList(userList, JdyVO.class);
        if (CollectionUtils.isEmpty(userList)) {
            PageResult<JdyVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, jdyList);
            return ResponseDTO.ok(pageResult);
        }

        List<TypeEntity> majorList = typeDao.selectByKey("pro_major");
        for (JdyVO user : jdyList){
//            List<OrderVO> orderVOList = orderDao.queryOrderByJdyId(user.getUserId());
//            List<BigDecimal> OrderPriceList = orderVOList.stream().map(OrderVO::getOrderPrice).collect(Collectors.toList());
//            Optional<BigDecimal> bigDecimal = OrderPriceList.stream().reduce(BigDecimal::add);
//            user.setAmount(bigDecimal.get());
            for (TypeEntity major : majorList) {
                if (major.getTypeId().equals(user.getMajorId())) {
                    user.setMajorName(major.getTypeName());
                }
            }
        }
        PageResult<JdyVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, jdyList);
        return ResponseDTO.ok(pageResult);
    }
    public ResponseDTO<PageResult<UserVO>> queryUser(UserQueryForm QueryForm) {
//        employeeQueryForm.setDeletedFlag(false);
        Page pageParam = SmartPageUtil.convert2PageQuery(QueryForm);
        List<UserVO> userList = userDao.queryByPage(pageParam, QueryForm);
        if (CollectionUtils.isEmpty(userList)) {
            PageResult<UserVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, userList);
            return ResponseDTO.ok(pageResult);
        }
        List<TypeEntity> majorList = typeDao.selectByKey("pro_major");
        for (UserVO user : userList){
            for (TypeEntity major : majorList) {
                if (major.getTypeId().equals(user.getMajorId())) {
                    user.setMajorName(major.getTypeName());
                }
            }
        }
        PageResult<UserVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, userList);
        return ResponseDTO.ok(pageResult);
    }
    public ResponseDTO<String> add(UserAddForm userAddDTO) {
        UserEntity alreadyEntity = userDao.getByPhone(userAddDTO.getPhone());
        UserEntity entity = SmartBeanUtil.copy(userAddDTO, UserEntity.class);
        if (alreadyEntity!= null) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST);
        }
        entity.setUserId(String.valueOf(IdGenerator.generateId()));
        entity.setRegisterTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        userDao.insert(entity);
        AmountEntity amountEntity = new AmountEntity();
        amountEntity.setRemainAmount(BigDecimal.ZERO);
        amountEntity.setTotalAmount(BigDecimal.ZERO);
        amountEntity.setUserId(entity.getUserId());
        amountDao.insert(amountEntity);
        return ResponseDTO.ok();
    }
    public ResponseDTO<String> updateUser(UserUpdateForm updateDTO) {
        UPDATE = true;
        String configId = updateDTO.getUserId();
        UserEntity entity = userDao.selectById(configId);
        if (null == entity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        entity = SmartBeanUtil.copy(updateDTO, UserEntity.class);
        List<UserEntity> alreadyEntity = userDao.selectByName(updateDTO.getName());
        if (null != alreadyEntity && alreadyEntity.contains(entity)) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST, "用户已存在");
        }
        if (updateDTO.isDel()==true){
            entity.setDel(false);
        }
        // 更新数据
//        entity = SmartBeanUtil.copy(updateDTO, ShopEntity.class);
        entity.setUpdateTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
//        UserUpdateForm updateForm = SmartBeanUtil.copy(entity, UserUpdateForm.class);
        userDao.updateByUserEntity(entity);
//        userloginService.updateSecondLoginCache(entity);
        return ResponseDTO.ok();
    }
    public ResponseDTO<String> deleteUser(UserUpdateForm updateDTO) {
        String configId = updateDTO.getUserId();
        UserEntity entity = userDao.selectById(configId);
        if (null == entity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 更新数据
        entity = SmartBeanUtil.copy(updateDTO, UserEntity.class);
        entity.setDel(true);
        userDao.updateById(entity);
        return ResponseDTO.ok();
    }

    public ResponseDTO<UserVO> queryById(Integer id) {
        UserEntity entity = userDao.selectByUserId(String.valueOf(id));
        return ResponseDTO.ok(SmartBeanUtil.copy(entity, UserVO.class));
    }
    public UserEntity getByPhone(String phone) {
        return userDao.getByPhone(phone);
    }

    public UserEntity getById(String id) {
            return userDao.selectByUserId(id);
    }
}
